package com.will.docker.exec.util;

import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerCertificates;
import com.spotify.docker.client.DockerCertificatesStore;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.ContainerConfig;
import com.spotify.docker.client.messages.ContainerInfo;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Paths;
import java.time.DateTimeException;

/**
 * docker操作类.
 * @author will
 */
public class DockerHelper {
    public static void execute(String ip,DockerAction dockerAction)throws Exception{
        DockerClient docker = DefaultDockerClient.builder().uri("https://".concat(ip).concat(":2375")).apiVersion("v1.30").dockerCertificates(new DockerCertificates(Paths.get("D:\\证书"))).build();
        dockerAction.action(docker);
        docker.close();
    }

    public static <T> T query(String ip,DockerQuery<T> dockerQuery)throws Exception{
        DockerClient docker = DefaultDockerClient.builder().uri("https://".concat(ip).concat(":2375")).apiVersion("v1.30").dockerCertificates(new DockerCertificates(Paths.get("D:\\证书"))).build();
        T result=dockerQuery.action(docker);
        docker.close();
        return result;
    }

    public interface DockerAction {
        void action(DockerClient docker) throws Exception;
    }

    public interface DockerQuery<T> {
        T action(DockerClient docker) throws Exception;
    }

    private static String getRealHourNum(int hour){
        String newTime = "";
        int hourNum = Integer.valueOf(hour) + 8;
        if(hourNum > 16){
            newTime = String.valueOf(hourNum-24);
        }else if(hourNum > 9 && hourNum < 16){
            newTime = String.valueOf(hourNum);
        }else{
            newTime = String.format("0%s",hourNum);
        }
        return newTime;
    }

    public static void main(String[] args) throws Exception{

        DockerClient docker =DefaultDockerClient.builder().uri(URI.create("https://192.168.19.130:2375")).dockerCertificates(new DockerCertificates(Paths.get("D:\\证书"))).build();

        try {
            //获取容器详情，输入参数是容器ID
            ContainerInfo containerInfo = docker.inspectContainer("bcf1d056a7b2");
            System.out.println(containerInfo.state());
            //docker.copyToContainer(new java.io.File("/Users/zwxu/source/").toPath(),"612cab2faa3f","/etc/apt/");
            //docker.commitContainer("612cab2faa3f","172.31.205.29/library/user","1.0",ContainerConfig.builder().build(),"first commit","zwxu5@iflytek.com");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
